package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.Them;
import com.sk.bilibili.bean.ThemBanner;
import com.sk.bilibili.bean.VideoSet;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Banner;
import com.sk.bilibili.mapper.BannerMapper;

/**
 * @author 邵康
 * @date 2021/11/23 19:49
 */
@Service
public class BannerService extends ServiceImpl<BannerMapper, Banner> {

    @Autowired
    private MinioService minioService;
    @Autowired
    private VideoSetService videoSetService;
    private static final String COVER_PATH = "banner/cover/%s.jpg";
    private static final Pattern COVER_PATTERN = Pattern.compile("/(banner/cover/.*jpg)");

    public R<Void> add(Banner banner) {
        banner.setCover(minioService.add(banner.getCoverFile(), COVER_PATH));
        save(banner);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        Banner temp = getById(id);
        minioService.delete(temp.getCover(), COVER_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Banner banner) {
        Banner temp = getById(banner.getId());
        String cover = minioService.update(COVER_PATH, COVER_PATTERN, temp.getCover(), banner.getCoverFile());
        banner.setCover(cover);
        updateById(banner);
        return R.success();
    }

    public R<IPage<Banner>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<List<Banner>> getBanner(Integer typeId) {
        QueryWrapper<Banner> queryWrapper = QueryWrapperUtils.eq("type_id", typeId);
        return R.success(list(queryWrapper));
    }

    public void updateBanner() {
        List<Banner> banners = list(null);
        QueryWrapper<VideoSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("praise_num");
        queryWrapper.last("limit "+banners.size());
        List<VideoSet> videoSets = videoSetService.list(queryWrapper);
        for (int i = 0; i < banners.size(); i++) {
            Banner banner = banners.get(i);
            banner.setUrl(String.format("video/%d",videoSets.get(i).getId()));
            updateById(banner);
        }
    }

}
